<?php
/**
 * 开放平台基础类文件 授权及消息通知的实现
 */
namespace app\common\helper\open;
use app\common\helper\open\OpenPlatformBaseHelper;
use app\common\model\GlobalDataModel;
use app\common\model\ShopModel;
use app\common\model\MiniappFreeModel;
class OpenPlatformHelper extends OpenPlatformBaseHelper{
  
    
   //申请免费认证
    public function  applyFree($params){
        $this->setTicket();
        
        return $this->app->component->registerMiniProgram($params);
    }
    
    /**
     * 启动票据验证
     */            
    public function ticket(){
         $response = $this->app->startPushTicket();
        // var_dump($response);
         if($response['errcode'] == 0){
             echo 'success';
             die;
         }
         echo  $response['errmsg'];die;
    }
    
    /**
     * 第三方平台事件接受
     */
    public function event(){        
        $openPlatform = $this->app;
        $server = $openPlatform->server;
         // 处理TICKET
        $server->push(function ($message) use($openPlatform) {
            
            switch ($message['InfoType']){
                case 'component_verify_ticket': //记录这个有用
                    $GlobalModel = new GlobalDataModel();
                    $GlobalModel->where('k','ticket')->save(['v'=> $message['ComponentVerifyTicket'],'last_time'=>time()]);
                    cache('ticket', $message['ComponentVerifyTicket']);
                    break;
                case 'unauthorized': //取消授权的时候
                    ShopModel::where('wx_app_id',$message['AuthorizerAppid'])->save(['status'=>-1]);
                    break;
                case 'notify_third_fasteregister': //免认证小程序
                    MiniappFreeModel::where([
                        ['code','=',$message['info']['code']],
                        ['status','=',0]
                    ])->save([
                        'status' => $message['status'] == 0 ? 1 : $message['status'],
                        'message' => $message['msg'].$message['status']
                    ]);
                    break;
            }
            return 'success';
        });
        
        $response = $server->serve();
        // 将响应输出
        $response->send(); exit;
    }
     
    /**
     * 第三方平台消息通知
     */
     public function message(){ //暂时不做处理
        $this->setTicket();
        $openPlatform = $this->app;
        $message = $openPlatform->server->getMessage();
        $userNames = [
            'gh_3c884a361561','gh_5ed48fac74c2','gh_bfb1e7317d12','gh_efc1408e2565','gh_cdbff4a75d10',
            'gh_8dad206e9538','gh_905ae9d01059','gh_393666f1fdf4','gh_39abb5d4e1b7','gh_7818dcb60240'
        ];
        if(empty($message['ToUserName'])) { //暂时不接受没有来源的
            echo 'success'; exit;
        }
        //全网发布检测流程
        if(in_array($message['ToUserName'], $userNames)){
             $appid = request()->param('appid');
             if($message['MsgType'] == 'event'){
                $officialAccount = $openPlatform->officialAccount($appid);
                $server = $officialAccount->server; 
               
                $server->push(function ($message){
                   
                    return $message['Event'].'from_callback';
                });
                $response = $server->serve();
                $response->send(); exit;
             }else{
                 if($message['Content'] == 'TESTCOMPONENT_MSG_TYPE_TEXT'){
                    $officialAccount = $openPlatform->officialAccount($appid);
                    $server = $officialAccount->server; 
                    $server->push(function ($message){
                        return $message['Content'].'_callback';
                    });
                    $response = $server->serve();
                    $response->send(); exit;
                 }else if(strpos($message['Content'], "QUERY_AUTH_CODE") > -1){
                     $ticket = trim(str_replace("QUERY_AUTH_CODE:", "", $message['Content']));
                     $authCode = $openPlatform->handleAuthorize($ticket);
                     $officialAccount = $openPlatform->officialAccount($authCode['authorization_info']['authorizer_appid'],$authCode['authorization_info']['authorizer_refresh_token']);
                     $officialAccount->customer_service->message($ticket.'_from_api')->from($message['ToUserName'])->to($message['FromUserName'])->send(); 
                     echo '';exit;
                 }
             } 
        }else{ //非全网发布检测
            if($message['MsgType'] == 'event'){
                switch ($message['Event']){
                    case 'weapp_audit_success':
                         ShopModel::where('wx_app_open_id',$message['ToUserName'])->save(['code_status'=>5]);
                        break;
                    case 'weapp_audit_fail':
                         ShopModel::where('wx_app_open_id',$message['ToUserName'])->save(['code_status'=>4,'error_msg'=>$message['Reason']]);
                        break;
                }
            }
            echo 'success'; exit;
        }
    }
}